package 练习05_用线程池改造异步查询订单和收货地址;

import java.util.concurrent.*;

/**
 * @ClassName: TestThreadSearch
 * @Author: AllenSun
 * @Date: 2022/3/21 下午10:57
 */
public class TestThreadPoolSearch2 {

    public static void getOrder() {
        try {
            Thread.sleep(1000);
            System.out.println("获取订单信息");
            ctl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void getAddress() {
        try {
            Thread.sleep(1000);
            System.out.println("获取地址信息");
            ctl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static final CountDownLatch ctl = new CountDownLatch(2);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor executor= new ThreadPoolExecutor(
                5,
                10,
                15,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>()
        );

        long start = System.currentTimeMillis();
        //异步执行
        executor.execute(() -> {
            getOrder();
        });
        executor.execute(() -> {
            getAddress();
        });

        //等待完成
        ctl.await(20, TimeUnit.SECONDS);//最多等待20秒，不管子线程完没完

        long end = System.currentTimeMillis();

        //花费时间：1053
        System.out.println("花费时间："+(end-start));

        executor.shutdown();

    }
}
